package HTTP

import (
	"SQL/myDB"
	"database/sql"
	"net/http"
)

//确定添加群成员：
//s groupID string,[memeberID string]
//r Message string,
//  nil
func confirmAddGroupMember(w http.ResponseWriter, req *http.Request) {
	var (
		code   int         = Success
		msg    string      = ""
		result interface{} = nil
	)
	defer func() {
		writeResponse(code, msg, result, w)
	}()

	err := initHandle(w, req)
	if err != nil {
		code = errParseForm
		msg = err.Error()
		return
	}

	groupID := req.FormValue("groupID")
	memberID := req.Form["memberID"]
	code, msg, result = dealConfirmAddGroupMember(groupID, memberID)
}

func dealConfirmAddGroupMember(groupID string, memberID []string) (code int, msg string, result interface{}) {
	if groupID == "" || len(memberID) == 0 {
		code = errEmtpyID
		msg = "groupID or memberID is empty!"
		return
	}
	code, msg = IsGroupID(groupID)
	if code != Success {
		return
	}

	db, err := myDB.GetDB()
	if err != nil {
		code = errOpenDB
		msg = err.Error()
		return
	}

	code, msg = judgeMembers(db, memberID)
	if code != Success {
		return
	}

	tx, err := db.Begin()
	if err != nil {
		code = errBeginTx
		msg = err.Error()
		return
	}

	defer func() {
		if code != Success {
			err := tx.Rollback()
			if err != nil {
				code = errEndTx
				msg = err.Error()
			}
		}
	}()

	err = myDB.TxExecMultiSql(tx, "insert into members(groupID,userID) values($2,$1)", memberID, groupID)
	if err != nil {
		code = errDBExecFailed
		msg = err.Error()
		return
	}

	err = tx.Commit()
	if err != nil {
		code = errEndTx
		msg = err.Error()
		return
	}

	return Success, "", nil
}

func judgeMembers(db *sql.DB, memberID []string) (code int, msg string) {
	stmt, err := db.Prepare("select isUser from objects where id=$1")
	if err != nil {
		code = errOpenDB
		msg = err.Error()
		return
	}
	defer stmt.Close()
	for _, val := range memberID {
		code, msg = judgeMember(stmt, val)
		if code != Success {
			return
		}
	}
	code = Success
	msg = ""
	return
}

func judgeMember(stmt *sql.Stmt, memberID string) (code int, msg string) {
	rows, err := stmt.Query(memberID)
	if err != nil {
		code = errDBExecFailed
		msg = err.Error()
		return
	}
	defer rows.Close()
	if !rows.Next() {
		code = errInvalidID
		msg = memberID + " is not exist"
		return
	}
	var isUser bool
	err = rows.Scan(&isUser)
	if err != nil {
		code = errRowsScan
		msg = err.Error()
		return
	}
	if !isUser {
		code = errInvalidID
		msg = memberID + " is not user"
		return
	}
	code = Success
	msg = ""
	return
}
